package com.example.cmpe277stockdata;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.cmpe277stockdata.RSSFeeds.NewsReader;
import com.example.cmpe277stockdata.beans.NewsBean;
import com.example.cmpe277stockdata.beans.RealTimeBean;
import com.example.cmpe277stockdata.beans.UserBean;
import com.example.cmpe277stockdata.constants.DataConstants;
import com.example.cmpe277stockdata.dataaccess.AzurePortfolio;
import com.example.cmpe277stockdata.dataaccess.PortFolioDB;

public class RealTimeAdapter extends ArrayAdapter<RealTimeBean>
{
	private int resourceId;
    private LayoutInflater inflater;
    private Context ctx;
    private List<RealTimeBean> resultData;
    public NewsReader reader = new NewsReader();
	public Intent intent;
	public ImageButton btnAdd;
	public UserBean user;
	public AzurePortfolio portfolioazure;
	
    public RealTimeAdapter(Context context, int resource,List<RealTimeBean> objects) {
		super(context, resource, objects);
		
		resourceId = resource; 
		inflater = LayoutInflater.from(context);
		ctx = context;
		resultData = objects;
		
		try {
			portfolioazure = new AzurePortfolio(ctx);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    
    public void setUserData(UserBean userData)
    {
    	this.user = userData;
    }

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		//return super.getView(position, convertView, parent);
		
		Log.d("RealTimeAdapter", "Inside getView function");
		
		/* create a new view of my layout and inflate it in the row */
        convertView = (RelativeLayout) inflater.inflate( resourceId, null );

        
        /* Extract the city's object to show */
        final RealTimeBean realData = resultData.get( position );
        
        if(realData == null)
        {
        	return null;
        }
        if(realData.getChange() < 0)
        {
        	convertView.setBackgroundColor(Color.RED);
        }
        else
        {
        	convertView.setBackgroundColor(Color.GREEN);	
        }
        
       
        // Take the TextView from layout and set the news Description 
        TextView txtTickerSymbol = (TextView) convertView.findViewById(R.id.txtTickerSymbol);
        txtTickerSymbol.setText(realData.getTickerSymbol());
        txtTickerSymbol.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				intent = new Intent(ctx, NewsActivity.class);
		    	NewsData newsData = new NewsData();
		    	newsData.execute(realData.getTickerSymbol(),realData.getCompany());			
			}
		});
                
        // Take the TextView from layout and set the news Link
        TextView txtStockValue = (TextView) convertView.findViewById(R.id.txtStockValue);
        txtStockValue.setText(Double.toString(realData.getStockValue()));
        txtStockValue.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				intent = new Intent(ctx, NewsActivity.class);
		    	NewsData newsData = new NewsData();
		    	newsData.execute(realData.getTickerSymbol(),realData.getCompany());			
			}
		});
       
        //realData.setSelected(false);
        Log.d("RealTimeAdapter", "Finished getView function");
        
        btnAdd = (ImageButton) convertView.findViewById(R.id.btnFavorite);
        if(user != null)
        {
        	if(realData.isSelected())
        		btnAdd.setBackgroundResource(R.drawable.filled_star);
        	else
        		btnAdd.setBackgroundResource(R.drawable.star_border);
        }
        //btnAdd.setBackgroundResource(R.drawable.star_border);
        
        btnAdd.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				ImageButton btnClicked =  (ImageButton)v;
				//PortFolioDB db = new PortFolioDB(ctx);
				if(realData.isSelected())
				{
					//If Login Not clicked . Prompt user to login
					if(user == null)
					{
						AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
						builder.setMessage("Please login to add to Portfolio! ")
						       .setCancelable(false)
						       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						        	   /*Intent intent = new Intent(ctx,MainActivity.class);
										ctx.startActivity(intent);*/
						           }
						       });
						AlertDialog alert = builder.create();
						alert.show();
						
					}
					else
					{
						//Item already stored in DB Remove that item
						/*db.open();
						db.removeData(realData.getTickerSymbol(),realData.getCompany(), user.getId(), user.getUserName());
						db.close();*/
						portfolioazure.removeData(realData.getTickerSymbol(), realData.getCompany(), user.getId(), user.getUserName());
						realData.setSelected(false);
						btnClicked.setBackgroundResource(R.drawable.star_border);
					}
					
				}
				else
				{
					//If Login Not clicked . Prompt user to login
					if(user == null)
					{
						AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
						builder.setMessage("Please login to add to Portfolio! ")
						       .setCancelable(false)
						       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						        	   /*Intent intent = new Intent(ctx,MainActivity.class);
										ctx.startActivity(intent);*/
						           }
						       });
						AlertDialog alert = builder.create();
						alert.show();
					}
					else
					{
						//Add item to DB
						//db.open();
						//db.addData(realData.getTickerSymbol(),realData.getCompany(), user.getId(), user.getUserName());
						//db.close();
						
						portfolioazure.addData(realData.getTickerSymbol(),realData.getCompany(),user.getId(),user.getUserName());
						realData.setSelected(true);
						btnClicked.setBackgroundResource(R.drawable.filled_star);
					}					
				}
			}
		});
        return convertView;
	}
	
	public class NewsData extends AsyncTask<String, Void, ArrayList<NewsBean>>
	{
		private String companyName;
		private String tickerSymbol;
		@Override
	    protected void onPostExecute(ArrayList<NewsBean> result) {
	        try{
	        	if(result != null)
	        	{   		
					intent.putExtra(DataConstants.NEWS_RESULT, result);
		        	intent.putExtra(DataConstants.COMPANY_NAME, companyName);
		        	intent.putExtra(DataConstants.TICKER_SYMBOL,tickerSymbol);
 					intent.putExtra(DataConstants.USER_DATA, user);
		        	ctx.startActivity(intent);
	        	}       	
	        }
	        catch(Exception e){
	            e.printStackTrace();
	        }
	     }

		@Override
		protected ArrayList<NewsBean> doInBackground(String... params) {
			ArrayList<NewsBean> result = null;
			tickerSymbol = params[0];
			companyName = params[1];
			
			result = reader.getNewsFields(params[0]);
			return result;
		}
		
	}
	
}
